package com.baozhun.mall.common.network

import com.baozhun.mall.common.BuildConfig
import com.baozhun.mall.common.model.enums.ApiEnvironment
import com.baozhun.mall.common.util.Constants
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.Utils
import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.google.gson.GsonBuilder
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.network.BaseNetworkApi
import me.hgj.jetpackmvvm.network.interceptor.CacheInterceptor
import me.hgj.jetpackmvvm.network.interceptor.LogInterceptor
import me.hgj.jetpackmvvm.util.log.HttpLoggingInterceptorM
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit


/**
 * 作者　: hegaojian
 * 时间　: 2019/12/23
 * 描述　: 网络请求构建器，继承BasenetworkApi 并实现setHttpClientBuilder/setRetrofitBuilder方法，
 * 在这里可以添加拦截器，设置构造器可以对Builder做任意操作
 */

class NetworkApi : BaseNetworkApi() {

    private val mCookieJar: PersistentCookieJar by lazy {
        PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(appContext))
    }

    companion object {
        val SERVER_URL = "${getApiHost()}/merchant-api/"

        //接口配置
//        private const val API_HOST_RELEASE = "https://common-api.houjimall.com"
//        private const val API_HOST_DEV = "https://dev-common-api.houjimall.com"
//        private const val API_HOST_TEST = "https://dev-common-api.houjimall.com"
        //buybuycat
        private const val API_HOST_RELEASE = "https://common-api.houjimall.com"
        private const val API_HOST_DEV = "http://111.229.218.72:16002"
        private const val API_HOST_TEST = "http://111.229.218.72:16002"

        //h5配置
//        private const val H5_HOST_RELEASE = "https://common-api.houjimall.com"
//        private const val H5_HOST_TEST = "https://dev-common-api.houjimall.com"
//        private const val H5_HOST_DEV = "https://dev-common-api.houjimall.com"
        //buybuycat
        private const val H5_HOST_RELEASE = "https://common-api.houjimall.com"
        private const val H5_HOST_TEST = "http://111.229.218.72:16005"
        private const val H5_HOST_DEV = "http://111.229.218.72:16005"

        val INSTANCE: NetworkApi by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            NetworkApi()
        }

        /**
         * 获取api host
         */
        private fun getApiHost(): String {
            return if (BuildConfig.BUILD_TYPE == "release") {
                API_HOST_RELEASE
            } else {
                when (SPUtils.getInstance().getInt(Constants.Common.API_TYPE, ApiEnvironment.TEST.type)) {
                    ApiEnvironment.RELEASE.type -> API_HOST_RELEASE
                    ApiEnvironment.TEST.type -> API_HOST_TEST
                    ApiEnvironment.DEV.type -> API_HOST_DEV
                    else -> {
                        API_HOST_RELEASE
                    }
                }
            }
        }
    }

    /**
     * 实现重写父类的setHttpClientBuilder方法，
     * 在这里可以添加拦截器，可以对 OkHttpClient.Builder 做任意操作
     */
    override fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder {
        builder.apply {
            //设置缓存配置 缓存最大10M
            cache(Cache(File(appContext.cacheDir, "cxk_cache"), 10 * 1024 * 1024))
            //添加Cookies自动持久化
            cookieJar(mCookieJar)
            //示例：添加公共heads 注意要设置在日志拦截器之前，不然Log中会不显示head信息
            addInterceptor(MyHeadInterceptor())
            addInterceptor(CommonParamsInterceptor())
            //添加缓存拦截器 可传入缓存天数，不传默认7天
            addInterceptor(CacheInterceptor())
            addInterceptor(TokenOutInterceptor())
            addInterceptor(ChuckerInterceptor(Utils.getApp()))
            // 日志拦截器
//            addInterceptor(LogInterceptor())
            if (BuildConfig.DEBUG)
                addInterceptor(HttpLoggingInterceptorM(LogInterceptor()))
            //超时时间 连接、读、写
            connectTimeout(15, TimeUnit.SECONDS)
            readTimeout(15, TimeUnit.SECONDS)
            writeTimeout(15, TimeUnit.SECONDS)
        }
        return builder
    }

    /**
     * 实现重写父类的setRetrofitBuilder方法，
     * 在这里可以对Retrofit.Builder做任意操作，比如添加GSON解析器，protobuf等
     */
    override fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder {
        return builder.apply {
            addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
        }
    }

}



